<template>
    <div class="px-8">
        <com-filterTable
            :ref="pageConfig.key"
            class=""
            :services="pageConfig.serviceHandle"
            :filter-form-config="pageConfig.formConfig"
            :filterInline="false"
            :params="{}"
            :filterCol="4"
            filterLabelWidth="90px"
            :table-border="true"
            :showFormFilter="true"
            :showRequestNum="false"
            :top-operation="pageConfig.topOperation"
            :table-column="pageConfig.columnConfig"
            :queryDataHandle="queryDataHandle"
            :dataFormatHandle="dataFormatHandle"
            :autoLoad="true"
        />
        <com-formDialog
            ref="dialog"
            v-bind="dialogData"
            @changeOut="changeOut"
            @cancel="dialogCancelHandle"
            @submit="submitHandle"
        >
        </com-formDialog>
    </div>
</template>

<script>
import { selectRoleList, createRole, updateRole, deleteRole, selectRolePermissionList, assignRolePermissions } from "@/service/api.js";
import { mainMenu } from '@/mock/menu.js';
import moment from "moment";
import TreeTable from '@/components/TreeTable/index.vue';
export default {
    name: "roleManage",
    components: { TreeTable },
    data() {
        return {
            activeName: "filterTable",
            comDialogData: {},
            batchSelected: [],
            permissionTreeData: [],
            permissionTreeColumns: [
                { label: '名称', value: 'name' }
            ],
            selectedPermissions: [],
            currentRoleId: null,
            showPermissionTree: false,
            pageConfig: {
                key: "filterTable",
                serviceHandle: (data) => {
                    return selectRoleList(data);
                },
                params: {},
                formConfig: [
                    { key: "id", label: "角色编号" },
                    { key: "name", label: "角色名称" },
                ],
                columnConfig: [
                    { type: "select" },
                    { value: "name", label: "角色名称" },
                    { value: "code", label: "角色编码" },
                    { value: "description", label: "描述" },
                    {
                        value: "createTime",
                        label: "创建时间",
                        width: 180,
                        formatter: (row) => {
                            return moment(row.createTime).format(
                                "YYYY-MM-DD HH:mm:ss"
                            );
                        },
                    },
                    {
                        value: "action",
                        type: "render",
                        width: 220,
                        label: "操作",
                        render: (h, { data: { row } }) => {
                            const editBtn = (
                                <el-button type="text" on-click={() => this.addOrEditHandle(row)}>修改</el-button>
                            );
                            const delBtn = (
                                <el-button type="text" on-click={() => this.deleteList([row])}>删除</el-button>
                            );
                            const permissionBtn = (
                                <el-button type="text" on-click={() => this.openPermissionDialog(row)}>分配权限</el-button>
                            );
                            return [editBtn, delBtn];
                        },
                    },
                ],
                topOperation: {
                    left: [
                        {
                            name: "新增",
                            key: "add",
                            type: "primary",
                            requireArguments: ["batchSelected", "filterForm"],
                            handle: (batchSelected) => {
                                this.addOrEditHandle();
                            },
                        },
                    ],
                },
            },
        };
    },
    computed: {
        dialogData() {
            let { comDialogData } = this;
            return {
                configs:
                    this[comDialogData.configName] || comDialogData.configs,
                ...comDialogData,
                showCanceltBut: true,
                showSubmitBut: true,
                slotRenders: comDialogData.slotRenders || {},
            };
        },
    },
    methods: {
        changeOut({ key, formData } = {}) {},
        dataFormatHandle(data) {
            return {
                list: data.data,
                total: data.data ? data.data.length : 0,
            };
        },
        queryDataHandle(params) {
            let temp = {
                ...params,
            };
            return temp;
        },
        loadList() {
            let ref = this.$refs[this.activeName];
            if (Array.isArray(ref)) {
                ref = ref[0];
            }
            ref.filterFormQueryHandle();
        },
        dialogCancelHandle() {
            this.$refs.dialog.close();
        },
        async submitHandle(data) {
            let handle = this.dialogData.submitHandle;
            handle = typeof handle !== "function" ? this[handle] : handle;
            if (handle) {
                let loading = await this.$store.dispatch("global/loading");
                handle(data)
                    .then((res) => {
                        loading.close();
                        this.$refs.dialog.close();
                        this.loadList();
                    })
                    .catch((e) => {
                        loading.close();
                    });
            }
        },
        // 新增或编辑
        addOrEditHandle(row) {
            this.showPermissionTree = false;
            this.comDialogData = {
                submitHandle: (data) => {
                    let handle = createRole;
                    let params = {
                        ...data,
                    }
                    if(row) {
                        handle = updateRole;
                        params.id = row.id;
                    }
                    return handle(params)
                },
                initFormData: row,
                configs: [
                    { key: "name", label: "角色名称", required: true, fullLine: true },
                    { key: "code", label: "角色编码", required: true, fullLine: true },
                    { key: "description", label: "描述" },
                    {
                        key: 'permissionIds',
                        label: '菜单权限',
                        fullLine: true,
                        type: "cascader",
                        props: {
                            options: mainMenu,
                            props: {
                                value: 'key',
                                label: 'name',
                                multiple: true,
                                emitPath: false
                            }
                        }
                    }
                ],
                activeRow: row,
                title: row?"修改角色":"新增角色",
                width: "600px",
                height: "260px",
                labelPosition: "left",
                labelWidth: "110px",
                col: 2,
            };
            this.$refs.dialog.show();
        },
        // 删除
        deleteList(list) {
            let params = {
                id: list.map(item => item.id).join(',')
            }
            this.$confirm("确定要删除吗？").then(() => {
                this.comDialogData = {
                    submitHandle: () => {
                        return deleteRole(params)
                    }
                }
                this.submitHandle();
            });
        },
        // 打开权限分配弹窗
        async openPermissionDialog(row) {
            // this.showPermissionTree = true;
            // this.currentRoleId = row.id;
            // // 权限树数据
            // this.permissionTreeData = this.transformMenuToTree(mainMenu);
            // // 查询已分配权限
            // const res = await selectRolePermissionList({ roleId: row.id });
            // if(res && res.data && Array.isArray(res.data.data)) {
            //     this.selectedPermissions = res.data.data.map(item => item.permissionCode);
            // } else {
            //     this.selectedPermissions = [];
            // }
            this.comDialogData = {
                submitHandle: async (data) => {
                    // 获取选中的权限key
                    
                    return await assignRolePermissions({ roleId: row.id, permissionIds:data.permissionIds });
                },
                configs: [
                    { key: "name", label: "角色名称", required: true, disabled: true, default: row.name, fullLine: true },
                    // { key: "code", label: "角色编码", required: true, disabled: true, value: row.code },
                    {
                        key: 'permissionIds',
                        label: '菜单权限',
                        fullLine: true,
                        type: "cascader",
                        props: {
                            options: mainMenu,
                            props: {
                                value: 'key',
                                label: 'name',
                                multiple: true,
                                emitPath: false
                            }
                        }
                    }
                ],
                activeRow: row,
                initFormData: row,
                title: "分配权限",
                width: "700px",
                height: "300px",
                labelPosition: "left",
                labelWidth: "110px",
                col: 2,
                slotRenders: {
                    expand: (h) => {
                        return null;
                    }
                }
            };
            this.$refs.dialog.show();
        },
        // 菜单数据转树结构
        transformMenuToTree(menu) {
            return menu.map(item => {
                const node = {
                    ...item,
                    key: item.key,
                    name: item.name,
                };
                if(item.children && item.children.length) {
                    node.children = this.transformMenuToTree(item.children);
                }
                return node;
            });
        },
    },
};
</script>
